package com.fmi.timedealer.moodgame;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.fmi.timedealer.R;
import com.fmi.timedealer.datamanager.IDataManager;
import com.fmi.timedealer.datamanager.SQLiteDataManager;
import com.fmi.timedealer.moodtracking.Mood;
import com.fmi.timedealer.moodtracking.TrackedMood;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MoodGameActivity extends Activity {

	private static final int BORDER_PADDING = 25;
	
	private DisplayMetrics displayMetrics;
	private Box gameBox;
	private BallView ballView;
	private ArrayList<MoodView> moods;
	private RelativeLayout gameLayout;
	
	private IDataManager dbManager = null;
	
	private SensorManager sensorManager = null;
	private Sensor orientationSensor = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.game);
		
		dbManager = new SQLiteDataManager("MyDB", this);
		
		gameLayout = (RelativeLayout)findViewById(R.id.mood_game_layout);
		
		// Get screen sizes
		displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        
        gameBox = new Box();
        gameBox.setMaxX(displayMetrics.widthPixels);
        gameBox.setMaxY(displayMetrics.heightPixels);
        
        // Get sensor
        sensorManager = (SensorManager)getSystemService(Activity.SENSOR_SERVICE);
        List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
        if (sensors.size() > 0) {
        	orientationSensor = sensors.get(0);
        } else {
        	orientationSensor = null;
        }
        
        addMoodViews(displayMetrics.widthPixels, displayMetrics.heightPixels);
        addBallView();
	}

	@Override
	protected void onPause() {
		super.onPause();
		
		sensorManager.unregisterListener(mSensorListener);
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		final Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			public void run() {
				sensorManager.registerListener(mSensorListener, orientationSensor, SensorManager.SENSOR_DELAY_FASTEST);
			}
		}, 1000);
	}
	
	private void addBallView() {
		
		ballView = new BallView(MoodGameActivity.this, displayMetrics, gameBox, moods);		
		ballView.setOnCollisionListener(mCollisionListener);
		
		gameLayout.addView(ballView);
	}
	
	private void addMoodViews(int displayWidth, int displayHeight) {
		
		moods = new ArrayList<MoodView>();
		Mood[] moodObjects = Mood.values();
		
		// Get bitmaps dimensions
		Bitmap icon = BitmapFactory.decodeResource(getResources(), moodObjects[0].getIcon());
		int width = icon.getWidth();
		int height = icon.getHeight();
		
		// Calculate places
		int rightIndex = displayWidth - width - BORDER_PADDING;
		int bottomIndex = displayHeight - height - BORDER_PADDING;
		int centerIndex = (displayWidth / 2) - (width / 2);
		
		// Top-left corner
		MoodView topLeftView = new MoodView(MoodGameActivity.this, moodObjects[0], BORDER_PADDING, BORDER_PADDING);
		moods.add(topLeftView);
		gameLayout.addView(topLeftView);
		
		// Top-right corner
		MoodView topRightView = new MoodView(MoodGameActivity.this, moodObjects[1], rightIndex, BORDER_PADDING);
		moods.add(topRightView);
		gameLayout.addView(topRightView);
		
		// Top-center
		MoodView topCenterView = new MoodView(MoodGameActivity.this, moodObjects[2], centerIndex, BORDER_PADDING);
		moods.add(topCenterView);
		gameLayout.addView(topCenterView);
		
		// Bottom-left corner
		MoodView bottomLeftView = new MoodView(MoodGameActivity.this, moodObjects[3], BORDER_PADDING, bottomIndex);
		moods.add(bottomLeftView);
		gameLayout.addView(bottomLeftView);
		
		// Bottom-right corner
		MoodView bottomRightView = new MoodView(MoodGameActivity.this, moodObjects[4], rightIndex, bottomIndex);
		moods.add(bottomRightView);
		gameLayout.addView(bottomRightView);
		
		// Bottom-center
		MoodView bottomCenterView = new MoodView(MoodGameActivity.this, moodObjects[5], centerIndex, bottomIndex);
		moods.add(bottomCenterView);
		gameLayout.addView(bottomCenterView);
	}
	
	private final BallView.OnCollisionListener mCollisionListener = new BallView.OnCollisionListener() {
		
		public void onCollision(MoodView moodView) {
			
			Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
			v.vibrate(100);
			
			boolean success = dbManager.updateMood(new TrackedMood(moodView.getMood().getCode(), new Date(), null));
			
			final Dialog dialog = new Dialog(MoodGameActivity.this);
            dialog.setContentView(R.layout.mood_game_dialog);
            dialog.setTitle("Your mood");
            dialog.setCancelable(true);
            
            if (success) {
            	Bitmap icon = BitmapFactory.decodeResource(getResources(), moodView.getMood().getIcon());
        		
            	Drawable img = getResources().getDrawable(moodView.getMood().getIcon());
            	img.setBounds(0, 0, icon.getWidth(), icon.getHeight());
            	
            	TextView tvText = (TextView)dialog.findViewById(R.id.mood_dialog_text);
            	tvText.setCompoundDrawables(img, null, null, null);
            	tvText.setText("Now you are " + moodView.getMood().getLabel());
            }
            
            Button btnOk = (Button)dialog.findViewById(R.id.mood_dialog_button);
            btnOk.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					dialog.cancel();
					finish();
				}
			});
            
            dialog.show();
		}
	};
	
	private final SensorEventListener mSensorListener = new SensorEventListener() {

		public void onAccuracyChanged(Sensor sensor, int accuracy) {}
		
		public void onSensorChanged(SensorEvent event) {
			
			switch (event.sensor.getType()) {
			case Sensor.TYPE_ORIENTATION: {
				ballView.updateOrientation(event.values);
			}
				break;
			}
		}
	};
}
